
module.exports = function ImageDisplay($scope, StorageService) {
    // state
    $scope.uploaded = null;
    $scope.uploadDone = true;

    // image clear
    $scope.clear = () => {
        $scope.uploaded = null;
    }

    // imiage upload
    $scope.uploadImage = ($files) => {
        if ($files.length) {
            $scope.uploadDone = false;
            console.log("file select___");
            console.log($files);
            $scope.uploaded = {
                progress: 0,
                status: '',
                href:''
            };
            $scope.uploaded.progress = 1;
            return StorageService.storeFile('image', $files, {
                filter: function(file) {
                    return /\.png$|\.jpg$/i.test(file.name)
                }
            })
            .progressed(function(e) {
                if (e.lengthComputable) {
                    $scope.uploaded.progress = e.loaded / e.total * 100 / 2 - 1;
                    $scope.uploaded.status = 'uploading';
                    console.log("_____image__uploading___" + $scope.uploaded.progress);
                }
            })
            .then(function(res) {
                $scope.uploaded.progress = 100 / 2;
                $scope.uploaded.status = 'uploaded';
                $scope.uploaded.href = res.data.resources.file.href

                console.log("image upload done___");
                console.log($scope.uploaded);

                // start push
                $scope.control
                .imageDisplay(res.data.resources.file.href)
                .progressed(result => {
                    $scope.uploaded.progress = 50 + result.progress / 2;
                    $scope.uploaded.status = 'pushing';
                })
                .then(result => {
                    $scope.uploadDone = true;
                    $scope.uploaded.progress = 100;
                    $scope.uploaded.status = 'done';
                });
            })
            .catch(function(err) {
                $scope.uploadDone = true;
                $scope.uploaded.progress = 0;
                $scope.uploaded.status = 'error';
            })
        }
        
    }
};